<template>
  <PageWrapper dense contentFullHeight contentClass="flex">
    <RoleTreeList class="w-1/4 xl:w-1/5 treeList" @select="handleSelect" />
    <div class="mt-2 mb-2 ml-1 w-3/4 xl:w-4/5 bg-white">
      <BasicTable
        @register="registerTable"
        @resize-column="handleResizeColumn"
        v-show="curCode != 'member' && curCode != ''"
      >
        <template #toolbar>
          <a-button type="primary" size="middle" @click="handleCreate" v-if="curCode != 'member'"
            >新增</a-button
          >
          <Popconfirm
            placement="bottom"
            title="确定删除吗？"
            ok-text="确定"
            cancel-text="取消"
            @confirm="getSelectRowKeyList"
          >
            <a-button type="primary" size="middle" v-if="curCode != 'member'">删除</a-button>
          </Popconfirm>
        </template>
        <template #deptJson="{ record }">
          <div v-if="record.deptJson && record.deptJson.length > 0">
            <div v-for="(item, index) in record.deptJson" :key="index">
              <Checkbox
                :checked="item.roleOfDept == 0 ? false : true"
                @change="(e) => getChange(e, record, index)"
              >
                {{ item.deptName }}</Checkbox
              >
            </div>
          </div>
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: '删除此账号',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'leftBottom',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </BasicTable>
      <div class="h-full flex justify-center items-center" v-show="curCode == 'member'">
        <Empty description="全部用户" />
      </div>
      <div class="h-full flex justify-center items-center" v-show="curCode == ''">
        <Empty description="请选择角色" />
      </div>
    </div>
    <SelectUser @register="registerModal" @success="handleInSave" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, h } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getListUserOfRole,
    getSetUserRoleOfDept,
    getAddRoleUser,
    getDelRoleUserBatch,
    getChangeUserOfRoleOrder,
  } from '/@/api/system/system';
  import { PageWrapper } from '/@/components/Page';
  import { Popconfirm, InputNumber, Checkbox, Empty } from 'ant-design-vue';
  import RoleTreeList from './roleTreeList.vue';
  import { useModal } from '/@/components/Modal';
  import { SelectUser } from '/@/components/CustomComp';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  export default defineComponent({
    components: {
      BasicTable,
      PageWrapper,
      RoleTreeList,
      TableAction,
      SelectUser,
      Popconfirm,
      InputNumber,
      Checkbox,
      Empty,
    },
    setup() {
      const { t } = useI18n();
      const { createMessage } = useMessage();
      const positionRef = ref<null | HTMLElement>(null);
      const curCode = ref('');
      const dataRef = ref<any>({});
      const tableColumns: any = [
        {
          title: '序号',
          dataIndex: 'orders',
          width: 60,
          customRender: ({ record }: any) => {
            if (!Reflect.has(record, 'pendingStatus')) {
              record.pendingStatus = false;
            }
            return h(InputNumber, {
              value: record.orders,
              loading: record.pendingStatus,
              style: { width: '60px' },
              onChange: (e) => {
                record.orders = e;
              },
              onBlur: () => {
                if (record.orders == record.oldOrders) {
                  return;
                }
                record.pendingStatus = true;
                getChangeUserOfRoleOrder({
                  roleCode: record.roleCode,
                  order: record.orders,
                  userName: record.userName,
                })
                  .then(() => {
                    createMessage.success(t('common.opSuccess'));
                    reload();
                  })
                  .catch(() => {
                    record.orders = record.oldOrders;
                  })
                  .finally(() => {
                    record.pendingStatus = false;
                  });
              },
            });
          },
        },
        {
          title: '用户名',
          dataIndex: 'name',
          width: 100,
          ellipsis: true,
        },
        {
          title: '真实姓名',
          dataIndex: 'realName',
          width: 150,
          ellipsis: true,
        },
        {
          title: '工号',
          dataIndex: 'account',
          width: 150,
          ellipsis: true,
        },
        {
          title: '性别',
          dataIndex: 'gender',
          width: 100,
          ellipsis: true,
        },
        {
          title: '所属部门',
          dataIndex: 'deptJson',
          align: 'left',
          width: 150,
          ellipsis: true,
          slots: { customRender: 'deptJson' },
        },
      ];

      const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys, setTableData }] =
        useTable({
          title: '成员列表',
          api: getListUserOfRole,
          immediate: false,
          rowKey: 'userName',
          columns: tableColumns,
          showIndexColumn: false,
          // formConfig: {
          //   labelWidth: 60,
          //   schemas: [],
          //   autoSubmitOnEnter: true,
          // },
          useSearchForm: false,
          showTableSetting: true,
          bordered: true,
          rowSelection: {
            type: 'checkbox',
          },
          searchInfo: {
            op: 'search',
            roleCode: curCode.value,
          }, //额外的参数
          beforeFetch: (info) => {
            let newInfo = info;
            newInfo.roleCode = curCode.value;
            return newInfo;
          },
          canResize: true,
          // resizeHeightOffset: 50,
          actionColumn: {
            width: 160,
            title: '操作',
            dataIndex: 'action',
            slots: { customRender: 'action' },
          },
          pagination: {
            pageSize: 50,
          },
        });

      function handleCreate() {
        if (!curCode.value) {
          createMessage.warning('请先选择角色');
          return;
        }
        openModal(true, {
          isUpdate: false,
        });
      }

      function getChange(e, record, index) {
        let roleOfDept = e.target.checked ? '2' : '0';
        let params = {
          roleCode: record.roleCode,
          deptCode: record.deptJson[index]['deptCode'],
          userName: record.userName,
          roleOfDept: roleOfDept,
        };
        getSetUserRoleOfDept(params).then(() => {
          handleSuccess();
          createMessage.success('操作成功');
        });
      }
      function getSelectRowKeyList() {
        let keys = getSelectRowKeys();
        if (keys.length == 0) {
          createMessage.warning('请选择数据');
          return;
        }
        let params = {
          userNames: keys.join(','),
          roleCode: curCode.value,
          roleDesc: dataRef.value?.name,
        };
        getDelRoleUserBatch(params).then(() => {
          handleSuccess();
        });
      }

      async function handleDelete(record) {
        let params = {
          userNames: record.userName,
          roleCode: record.roleCode,
          roleDesc: dataRef.value?.name,
        };
        await getDelRoleUserBatch(params).then(() => {
          handleSuccess();
        });
      }

      function handleSelect(code = '', node) {
        console.log('code', code, 'node', node);
        dataRef.value = node;
        curCode.value = code;
        if (curCode.value == 'member') {
          setTableData([]);
        } else {
          handleSuccess();
        }
      }

      //调入
      const [registerModal, { openModal }] = useModal();

      async function handleInSave(data) {
        //选择用户后的回调
        let params = {
          userNames: '',
          userRealNames: '',
          roleCode: curCode.value,
          roleDesc: dataRef.value?.name,
        };
        let userNames = ref<any>([]);
        let userRealNames = ref<any>([]);
        data.forEach((item) => {
          userNames.value.push(item.name);
          userRealNames.value.push(item.realName);
        });
        params.userNames = userNames.value.join(',');
        params.userRealNames = userRealNames.value.join(',');
        getAddRoleUser(params).then(() => {
          handleSuccess();
        });
      }

      function handleSuccess() {
        setSelectedRowKeys([]);
        reload();
      }

      onMounted(async () => {
        // reload();
      });

      return {
        registerTable,
        handleCreate,
        handleDelete,
        handleSuccess,
        handleSelect,
        getSelectRowKeyList,
        registerModal,
        handleInSave,
        positionRef,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        getChange,
        curCode,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::v-deep .vben-basic-table-form-container .ant-form {
    padding: 0;
    margin-bottom: 10px;
  }
  ::v-deep .vben-basic-table-form-container {
    padding-bottom: 0;
  }
</style>
